﻿using System;
using System.IO;
using System.Collections;

/// <summary>
/// Summary description for HtmlParse.
/// </summary>
public class HtmlParse
{
    public HtmlParse()
    {
    }
    public string RemoveSize(string strResult, string size)
    {
        int indexofsize = strResult.ToUpper().IndexOf("font-size:".ToUpper());
        while (indexofsize > 0)
        {
            for (int i = indexofsize; i < indexofsize + 15; i++)
            {
                if (i >= strResult.Length - 4) break;
                if (strResult.Substring(i, 2).ToUpper() == "pt".ToUpper())
                {
                    strResult = strResult.Substring(0, indexofsize) + strResult.Substring(i);
                    indexofsize = i;
                    break;
                }
            }
            indexofsize++;
            if (indexofsize == 0) break;
            indexofsize = strResult.ToUpper().IndexOf("font-size:".ToUpper(), indexofsize);
        }
        //if(strResult.IndexOf("<br>")==strResult.Length-4)strResult=strResult.Substring(0,strResult.Length-4);
        //strResult="<span style='font-size:"+size+"'>"+strResult+"</span>";
        return strResult;
    }
    public string TrimTag(string TagName, string Content)
    {
        //Trim htmlTag of content
        string strResult = Content.Trim();
        strResult = strResult.Replace("\r\n", "");
        while (strResult.ToUpper().IndexOf("</P>") == 0)
            strResult = strResult.Substring(4);
        while (strResult.ToUpper().IndexOf("<" + TagName.ToUpper()) == 0)
        {
            int pos = strResult.IndexOf(">");
            strResult = strResult.Substring(pos + 1);
            pos = strResult.ToUpper().LastIndexOf("</" + TagName.ToUpper());
            if (pos > 0)
                strResult = strResult.Substring(0, pos);
        }
        int index = strResult.ToUpper().IndexOf("<BR>");
        if ((index >= strResult.Length - 6) && (index > 0))
        {
            strResult = strResult.Substring(0, index);
        }
        index = strResult.ToUpper().IndexOf("</BR>");
        if ((index >= strResult.Length - 6) && (index > 0))
        {
            strResult = strResult.Substring(0, index);
        }
        return strResult;
    }
    private string SwapSrc(string content)
    {
        string result = "";
        string src1 = GetValue(content, "src");
        string src2 = GetValue(content, "name");
        result = ReplaceValue("src", content, src2, src1);
        result = ReplaceValue("name", result, src1, src2);
        return result;
    }
    public string SwapEquationComment(string content)
    {
        string s = content, strResult = "";
        int pos = 0;
        while (true)
        {
            pos = s.IndexOf("<IMG id=testpro");
            if (pos < 0)
            {
                strResult = strResult + s;
                break;
            }
            else
            {
                int endpos = GetEndTagPos(pos, s);
                if (endpos > 0)
                {
                    string strcontent = s.Substring(pos, endpos - pos + 1);
                    if (pos > 0) strResult += s.Substring(0, pos);
                    if (endpos + 1 < s.Length)
                        s = s.Substring(endpos + 1);
                    else
                        s = "";
                    strResult += SwapSrc(strcontent);
                }

            }

        }
        return strResult;
    }

    string flashPath = "../JavaScript/mediaplayer/flashmediaelement.swf";
    //NewSplitChar='/'
    //FindSplitChar='/'
    //htmlTag="img"
    //SkipString="ShowEq.ashx?"
    public string ReplacePathClientServer(Char NewSplitChar, Char FindSplitChar, string htmlTag, string Skipstring, string newPath, string valName, string content)
    {
        string strTmp = content.ToUpper();
        string strResult = "";
        int startpos = 0, currentpos = 0;
        if (content.Length == 0) return "";
        while (startpos >= 0)
        {
            if (startpos == 0) startpos = -1;
            startpos = strTmp.IndexOf("<" + htmlTag.ToUpper(), startpos + 1);
            if (startpos < 0)
            {
                strResult += content.Substring(currentpos);
                break;
            }
            int endpos = GetEndTagPos(startpos, strTmp);
            if (strTmp.IndexOf(Skipstring.ToUpper(), startpos, endpos - startpos) > 0)
            {
                startpos = endpos;
            }
            else
            {
                string strTag = content.Substring(startpos, endpos - startpos + 1);
                string oldVal = GetValue(strTag, valName.ToUpper());
                string filename = System.IO.Path.GetFileName(oldVal);
                if (htmlTag.ToLower() == "img")
                {
                    strTag = ReplaceValue(valName, strTag, newPath + NewSplitChar.ToString() + filename, strTag);
                    strResult += content.Substring(currentpos, startpos - currentpos) + strTag;
                    startpos = endpos;
                    currentpos = startpos + 1;
                }
                else
                {
                    string ext = Path.GetExtension(filename).Trim().ToLower();
                    bool isAudio = false;
                    switch (ext)
                    {
                        case ".wav":
                        case ".mp3":
                        case ".wma":
                            isAudio = true;
                            break;
                    }
                    if (isAudio)
                    {
                        strTag = "<div>";
                        strTag += "<audio id='" + Path.GetFileNameWithoutExtension(filename) + @"' type='audio/mp3' controls='controls'>
                                       <source type='audio/mp3' src='" + newPath + NewSplitChar.ToString() + filename + @"'></source>";
                        //"<source src='" + newPath + NewSplitChar.ToString() + filename + "'></source>";
                        strTag += @" <object width='320' height='240' type='application/x-shockwave-flash' data='" + flashPath + @"'>
                                            <param name='movie' value='" + flashPath + @"' />
                                            <param name='flashvars' value='controls=true&file=" + newPath + NewSplitChar.ToString() + filename + @"' />
                                        </object>";
                        strTag += "</audio></div>";
                        strTag += "<script type='text/javascript'>$(function() {$('#" + Path.GetFileNameWithoutExtension(filename) + "').mediaelementplayer({alwaysShowControls: false,features: ['playpause','volume'],audioVolume: 'horizontal',audioWidth: 400,audioHeight: 120});});</script>";
                        strResult += content.Substring(currentpos, startpos - currentpos) + strTag;

                        startpos = endpos + 11;
                        currentpos = startpos + 1;
                    }
                }

            }
        }
        return strResult;
    }

    private String ReplaceValue(String valName, String content, String NewVal, String FindString)
    {
        if (content.IndexOf(FindString) < 0) return content;
        String tmpContent = content.ToUpper();
        int indexval = tmpContent.IndexOf(valName.ToUpper());
        int startpos = tmpContent.IndexOf(valName.ToUpper());
        if (startpos < 0) return content;
        startpos = tmpContent.IndexOf("=", startpos + valName.Length) + 1;
        int stoppos = startpos;
        int beginvaluepos = 0, endvaluepos = 0;
        String commentchar = "\"";
        bool bfind = false;
        String strResult = content;
        for (int i = startpos; i < tmpContent.Length - 1; i++)
        {
            if ((Char.IsLetterOrDigit(tmpContent, i) || (tmpContent[i].ToString() == "'") || (tmpContent[i].ToString() == "\"")) && (!bfind))
            {
                beginvaluepos = i;
                bfind = true;
                commentchar = tmpContent[i].ToString();
                i++;
            }
            if (((((Char.IsWhiteSpace(tmpContent, i) && (commentchar != "'") || (tmpContent[i].ToString() == ">")) && (commentchar != "\"")) || (tmpContent[i].ToString() == "\"") || (tmpContent[i].ToString() == "'"))) && (bfind))
            {
                endvaluepos = i - 1;
                if ((commentchar == "'") || (commentchar == "\""))
                {
                    if (NewVal != "")
                        strResult = content.Substring(0, beginvaluepos + 1) + NewVal + content.Substring(endvaluepos + 1);
                    else
                        strResult = content.Substring(0, indexval - 1) + content.Substring(endvaluepos + 1);
                }
                else
                {
                    if (NewVal != "")
                        strResult = content.Substring(0, beginvaluepos) + NewVal + content.Substring(endvaluepos + 1);
                    else
                        strResult = content.Substring(0, indexval - 1) + content.Substring(endvaluepos + 1);
                }
                break;
            }
        }

        return strResult;

    }
    //		private string ReplaceValue(string valName,string content,string NewVal,string FindString)
    //		{
    //			if(content.IndexOf(FindString)<0)return content;
    //			string tmpContent=content.ToUpper();
    //			int startpos=tmpContent.IndexOf(valName.ToUpper());
    //			if(startpos<0)return content;
    //			startpos=tmpContent.IndexOf("=",startpos+valName.Length)+1;
    //			int stoppos=startpos;
    //			string commentchar="\"";
    //			bool bfind=false;
    //			for(int  i=startpos;i<tmpContent.Length;i++)
    //			{
    //				if((bfind)&&(tmpContent[i].ToString()==commentchar))
    //				{
    //					stoppos=i;
    //					break;
    //				}
    //				if((!bfind)&&((tmpContent[i].ToString()=="\"")||(tmpContent[i].ToString()=="'")))
    //				{
    //					commentchar=tmpContent[i].ToString();
    //					startpos=i+1;
    //					bfind=true;
    //				}
    //
    //			}	
    //			return content.Substring(0,startpos)+NewVal+content.Substring(stoppos);			
    //			
    //		}
    //Vd
    //TagName="img"
    //valName="src"
    //FindString=TenAnh
    //NewVal="../../Images/"
    public string ReplaceTagValue(string tagName, string valName, string FindString, string NewVal, string content, string skipstring)
    {
        string strResult = content.ToUpper();
        string strNewResult = "";
        int i = 0, i1 = 0;
        while (true)
        {
            i1 = i;
            i = strResult.IndexOf("<" + tagName.ToUpper(), i);
            if (i < 0)
            {
                strNewResult += content.Substring(i1);
                break;
            }
            int endpos = GetEndTagPos(i, strResult);
            if (strResult.IndexOf(skipstring.ToUpper(), i, endpos - i + 1) >= 0)
            {
                strNewResult += content.Substring(i1, endpos - i1);
                i = endpos;
            }
            else
            {
                strNewResult += content.Substring(i1, i - i1) + ReplaceValue(valName, content.Substring(i, endpos - i), NewVal, FindString);
                i = endpos;
            }
        }
        return strNewResult;
    }

    private int GetEndTagPos(int startPos, string content)
    {
        int count = 0, result = -1;
        for (int i = startPos; i < content.Length; i++)
        {
            if (content[i].ToString() == "<")
            {
                count++;
            }
            if (content[i].ToString() == ">")
            {
                count--;
            }
            if (count == 0)
            {
                result = i;
                break;
            }
        }
        return result;
    }
    //		private string GetValue(string content,string valName)
    //		{
    //			string tmpContent=content.ToUpper();
    //			int startpos=tmpContent.IndexOf(valName.ToUpper());
    //			if(startpos<0)return "";
    //			startpos=tmpContent.IndexOf("=",startpos+valName.Length)+1;
    //			int stoppos=startpos;
    //			string commentchar="\"";
    //			bool bfind=false;
    //			bool bcomment=false;
    //			for(int  i=startpos;i<tmpContent.Length;i++)
    //			{
    //				if((bfind)&&(tmpContent[i].ToString()==commentchar))
    //				{
    //					stoppos=i;
    //					break;
    //				}
    //				if((!bfind)&&((tmpContent[i].ToString()=="\"")||(tmpContent[i].ToString()=="'")))
    //				{
    //					commentchar=tmpContent[i].ToString();
    //					startpos=i+1;
    //					bfind=true;
    //					bcomment=true;
    //				}
    //				else
    //				{
    //					if(!bcomment)
    //					{
    //						if((tmpContent[i].ToString()!=" ")&&(tmpContent[i].ToString()!="\t")&&(!bfind))
    //						{
    //							startpos=i;
    //							bfind=true;
    //						}
    //						else
    //						{
    //							if(((tmpContent[i].ToString()==" ")||(tmpContent[i].ToString()=="\t"))&&(bfind))
    //							{
    //								stoppos=i;
    //								break;
    //							}
    //						}
    //					}
    //				}
    //
    //			}	
    //			try
    //			{
    //				return content.Substring(startpos,stoppos-startpos);
    //			}
    //			catch
    //			{
    //			}
    //			return "";
    //			
    //		}
    private String GetValue(String content, String valName)
    {
        String tmpContent = content.ToUpper();
        int startpos = tmpContent.IndexOf(valName.ToUpper());
        if (startpos < 0) return "";
        int beginvaluepos = 0, endvaluepos = 0;
        startpos = tmpContent.IndexOf("=", startpos + valName.Length) + 1;
        int stoppos = startpos;
        String commentchar = "\"";
        bool bfind = false;
        String strResult = "";
        for (int i = startpos; i < tmpContent.Length - 1; i++)
        {
            if ((Char.IsLetterOrDigit(tmpContent, i) || (tmpContent[i].ToString() == "'") || (tmpContent[i].ToString() == "\"")) && (!bfind))
            {
                beginvaluepos = i;
                bfind = true;
                commentchar = tmpContent[i].ToString();
                i++;
            }
            if (((((Char.IsWhiteSpace(tmpContent, i) && (commentchar != "'") || (tmpContent[i].ToString() == ">")) && (commentchar != "\"")) || (tmpContent[i].ToString() == "\"") || (tmpContent[i].ToString() == "'"))) && (bfind))
            {
                endvaluepos = i - 1;
                if ((commentchar == "'") || (commentchar == "\""))
                {
                    strResult = content.Substring(beginvaluepos + 1, endvaluepos - beginvaluepos);
                }
                else
                {
                    strResult = content.Substring(beginvaluepos, endvaluepos - beginvaluepos + 1);
                }
                break;
            }
        }
        return strResult;

    }
    public System.Collections.Generic.List<string> GetTagValue(string tagName, string valName, string content, string skipstring)
    {
        string strResult = content.ToUpper();
        System.Collections.Generic.List<string> arr = new System.Collections.Generic.List<string>();
        int i = 0;
        while (true)
        {
            i = strResult.IndexOf("<" + tagName.ToUpper(), i);
            if (i < 0) break;
            int endpos = GetEndTagPos(i, strResult);
            if (strResult.IndexOf(skipstring.ToUpper(), i, endpos - i + 1) >= 0)
            {
                i = endpos;
            }
            else
            {
                string itemContent = content.Substring(i, endpos - i + 1);
                string itemVal = GetValue(itemContent, valName.ToUpper());
                if (itemVal.Trim() != "")
                {
                    arr.Add(itemVal);
                }
                i = endpos;
            }
        }
        return arr;
    }
    public string RemoveHtmlTag(string tagName, string FindValue, string content)
    {
        string strResult = content.ToUpper();
        string strNewResult = "";
        int i = 0, i1 = 0;
        while (true)
        {
            i1 = i;
            i = strResult.IndexOf("<" + tagName.ToUpper(), i);
            if (i < 0)
            {
                strNewResult += content.Substring(i1);
                break;
            }
            int endpos = GetEndTagPos(i, strResult);
            if (strResult.IndexOf(FindValue.ToUpper(), i, endpos - i + 1) >= 0)
            {
                i = endpos;
            }
            else
            {
                i = endpos;
                strNewResult += content.Substring(i1, i - i1);
            }
        }
        return strNewResult;
    }
    public string RemoveTag(string Content)
    {
        //Remove all html tag remain text in content
        string strResult = Content;
        int startpos = strResult.IndexOf("<");
        while (startpos >= 0)
        {
            startpos = strResult.IndexOf("<");
            if (startpos < 0) break;
            int pos = strResult.IndexOf(">", startpos);
            if (pos < 0)
                break;
            string strTMP = strResult;
            if (startpos >= 0)
                strResult = strTMP.Substring(0, startpos);
            if (pos < strTMP.Length)
                strResult += strTMP.Substring(pos + 1);
        }
        strResult = strResult.Replace("\t", "");
        strResult = strResult.Replace("\n", "");
        strResult = strResult.Replace("\r", "");
        return strResult;
    }
    //		public string RemoveVmlContent(string content)
    //		{
    //			string strResult=content.ToUpper();	
    //			string strNewResult="";			
    //			int i=0,i1=0;
    //			while(true)
    //			{
    //				i1=i;			
    //				i=strResult.IndexOf("<!--[if gte vml 1]>".ToUpper(),i);
    //				if(i<0)
    //				{
    //				
    //					strNewResult+=content.Substring(i1);
    //					break;	
    //				}
    //				int endpos=strResult.IndexOf("<![endif]-->".ToUpper(),i);
    //				//string strContent=content.Substring(i+"<!--[if gte vml 1]>".Length,endpos-i-"<!--[if gte vml 1]>".Length);
    //				int imgpos=strResult.IndexOf("<![if !vml]>".ToUpper(),endpos);
    //				if(imgpos>0)
    //				{
    //					int endimgpos=strResult.IndexOf("<![endif]>".ToUpper(),imgpos);					
    //					string strImg=content.Substring(imgpos+"<![if !vml]>".Length,endimgpos-imgpos-"<![if !vml]>".Length);
    //					int imagedatapos= strResult.IndexOf("<v:imagedata".ToUpper(),i);			
    //					int imagedataendpos=strResult.IndexOf("/>",imagedatapos)+2;
    //					//string strtmp=	content.Substring(i1,imagedatapos-i1);
    //					strNewResult+=content.Substring(i1,imagedatapos-i1)+strImg+content.Substring(imagedataendpos,imgpos-imagedataendpos);
    //					i=endimgpos+"<![endif]>".Length;
    //				}
    //				else
    //				{
    //					strNewResult+=content.Substring(i1,i-i1);
    //					i=endpos+"<![endif]-->".Length;	
    //				}
    //			}	
    //			strNewResult=RemoveVmlTag(strNewResult,"<!--[if gte vml 1]>","<![endif]-->");
    //			return strNewResult;
    //		}
    public String RemoveVmlContent(String content)
    {
        String strResult = content.ToUpper();
        String strNewResult = "";
        int i = 0, i1 = 0;
        while (true)
        {
            i1 = i;
            i = strResult.IndexOf("<!--[if gte vml 1]>".ToUpper(), i);
            if (i < 0)
            {

                strNewResult += content.Substring(i1);
                break;
            }
            int endpos = strResult.IndexOf("<![endif]-->".ToUpper(), i);
            //String strContent=content.Substring(i+"<!--[if gte vml 1]>".Length,endpos-i-"<!--[if gte vml 1]>".Length);
            int imgpos = strResult.IndexOf("<![if !vml]>".ToUpper(), endpos);
            if (imgpos > 0)
            {
                int endimgpos = strResult.IndexOf("<![endif]>".ToUpper(), imgpos);
                String strImg = content.Substring(imgpos + "<![if !vml]>".Length, endimgpos - imgpos - "<![if !vml]>".Length);
                int imagedatapos = strResult.IndexOf("<v:imagedata".ToUpper(), i);
                int imagedataendpos = strResult.IndexOf("/>", imagedatapos) + 2;
                int height = 0;
                int indexsub = strResult.LastIndexOf("<SUB>", i);
                int indexendsub = strResult.IndexOf("</SUB>", imagedataendpos);
                try
                {
                    height = Convert.ToInt32(GetValue(strImg, "height"));
                }
                catch { }
                try
                {
                    if ((indexsub > i1) && (imagedatapos - indexsub - 5 > 0))
                    {
                        strNewResult += content.Substring(i1, indexsub - i1) + content.Substring(indexsub + 5, imagedatapos - indexsub - 5) +
                            "<SPAN style='POSITION: relative; TOP: 0pt; mso-text-raise: -20.0pt'>" +
                            "<v:shape align='top' height='" + Convert.ToString(height + 10) + "' id=_x0000_i1025 type='#_x0000_t75'>" +
                            InsertAtribute(ReplaceValue("width", ReplaceValue("width", strImg, "", "width"), "", "height"), "align", "absmiddle") +
                            "</v:shape></SPAN>" +
                            content.Substring(imagedataendpos, imgpos - imagedataendpos);
                        i = indexendsub + "</SUB>".Length;
                    }
                    else
                    {

                        strNewResult += content.Substring(i1, imagedatapos - i1) +
                            "<SPAN style='POSITION: relative; TOP: 0pt; mso-text-raise: -20.0pt'>" +
                            "<v:shape align='top' id=_x0000_i1025 type='#_x0000_t75'>" +
                            InsertAtribute(ReplaceValue("width", ReplaceValue("width", strImg, "", "width"), "", "height"), "align", "absmiddle") +
                            "</v:shape></SPAN>" +
                            content.Substring(imagedataendpos, imgpos - imagedataendpos);

                        i = endimgpos + "<![endif]>".Length;
                    }
                }
                catch
                {
                    strNewResult += content.Substring(i1, i - i1);
                    i = endpos + "<![endif]-->".Length;
                }
            }
            else
            {
                strNewResult += content.Substring(i1, i - i1);
                i = endpos + "<![endif]-->".Length;
            }
        }
        strNewResult = RemoveVmlTag(strNewResult, "<!--[if gte vml 1]>", "<![endif]-->");
        return strNewResult;
    }
    public string RemoveVmlTag(string content, string opentag, string endtag)
    {
        string strResult = content.ToUpper();
        string strNewResult = "";
        int i = 0, i1 = 0;
        while (true)
        {
            i1 = i;
            i = strResult.IndexOf(opentag.ToUpper(), i);
            if (i < 0)
            {
                strNewResult += content.Substring(i1);
                break;
            }
            int endpos = strResult.IndexOf(endtag.ToUpper(), i);
            strNewResult += content.Substring(i1, i - i1) + content.Substring(i + opentag.Length, endpos - i - opentag.Length);
            i = endpos + endtag.Length;
        }
        return strNewResult;
    }
    private String InsertAtribute(String content, String AtributeName, String AtributeValue)
    {
        String strtmp = content.ToUpper();
        if (strtmp.IndexOf(AtributeName.ToUpper()) > 0)
        {
            ReplaceValue(strtmp, content, AtributeValue, AtributeName);
        }
        else
        {
            int index = 0;
            while (index < strtmp.Length)
            {
                if (Char.IsWhiteSpace(strtmp, index))
                {
                    return content.Substring(0, index + 1) + AtributeName + "='" + AtributeValue + "' " + content.Substring(index + 1);
                }
                index++;
            }
        }
        return content;
    }

    public string RemoveVmlContent(string content, string opentag, string endtag)
    {
        string strResult = content.ToUpper();
        string strNewResult = "";
        int i = 0, i1 = 0;
        while (true)
        {
            i1 = i;
            i = strResult.IndexOf(opentag.ToUpper(), i);
            if (i < 0)
            {
                strNewResult += content.Substring(i1);
                break;
            }
            int endpos = strResult.IndexOf(endtag.ToUpper(), i);
            strNewResult += content.Substring(i1, i - i1);
            i = endpos + endtag.Length;
        }
        return strNewResult;
    }

}

